// IndexedDB 数据库操作
let db;
const DB_NAME = 'contactsDB';
const STORE_NAME = 'contacts';
const DB_VERSION = 1;

// 初始化数据库
function initDatabase() {
  return new Promise((resolve, reject) => {
    const request = indexedDB.open(DB_NAME, DB_VERSION);

    request.onupgradeneeded = (event) => {
      db = event.target.result;
      const store = db.createObjectStore(STORE_NAME, { keyPath: 'id', autoIncrement: true });
      store.createIndex('name', 'name', { unique: false });
      store.createIndex('phone', 'phone', { unique: false });
      console.log('数据库升级完成');
    };

    request.onsuccess = (event) => {
      db = event.target.result;
      console.log('数据库连接成功');
      resolve();
    };

    request.onerror = (event) => {
      console.error('数据库连接失败:', event.target.error);
      reject(event.target.error);
    };
  });
}

// 添加联系人
function addContact(contact) {
  return new Promise((resolve, reject) => {
    const transaction = db.transaction([STORE_NAME], 'readwrite');
    const store = transaction.objectStore(STORE_NAME);
    const request = store.add(contact);

    request.onsuccess = (event) => {
      console.log('联系人添加成功:', event.target.result);
      resolve(event.target.result);
    };

    request.onerror = (event) => {
      console.error('联系人添加失败:', event.target.error);
      reject(event.target.error);
    };
  });
}

// 获取所有联系人
function getAllContacts() {
  return new Promise((resolve, reject) => {
    const transaction = db.transaction([STORE_NAME], 'readonly');
    const store = transaction.objectStore(STORE_NAME);
    const request = store.getAll();

    request.onsuccess = (event) => {
      resolve(event.target.result);
    };

    request.onerror = (event) => {
      console.error('获取联系人失败:', event.target.error);
      reject(event.target.error);
    };
  });
}

// 根据ID获取联系人
function getContactById(id) {
  return new Promise((resolve, reject) => {
    const transaction = db.transaction([STORE_NAME], 'readonly');
    const store = transaction.objectStore(STORE_NAME);
    const request = store.get(id);

    request.onsuccess = (event) => {
      resolve(event.target.result);
    };

    request.onerror = (event) => {
      console.error('获取联系人失败:', event.target.error);
      reject(event.target.error);
    };
  });
}

// 更新联系人
function updateContact(contact) {
  return new Promise((resolve, reject) => {
    const transaction = db.transaction([STORE_NAME], 'readwrite');
    const store = transaction.objectStore(STORE_NAME);
    const request = store.put(contact);

    request.onsuccess = (event) => {
      console.log('联系人更新成功:', event.target.result);
      resolve(event.target.result);
    };

    request.onerror = (event) => {
      console.error('联系人更新失败:', event.target.error);
      reject(event.target.error);
    };
  });
}

// 根据ID删除联系人
function deleteContact(id) {
  return new Promise((resolve, reject) => {
    const transaction = db.transaction([STORE_NAME], 'readwrite');
    const store = transaction.objectStore(STORE_NAME);
    const request = store.delete(id);

    request.onsuccess = (event) => {
      console.log('联系人删除成功:', id);
      resolve();
    };

    request.onerror = (event) => {
      console.error('联系人删除失败:', event.target.error);
      reject(event.target.error);
    };
  });
}

// 删除所有联系人
function deleteAllContacts() {
  return new Promise((resolve, reject) => {
    const transaction = db.transaction([STORE_NAME], 'readwrite');
    const store = transaction.objectStore(STORE_NAME);
    const request = store.clear();

    request.onsuccess = (event) => {
      console.log('所有联系人已删除');
      resolve();
    };

    request.onerror = (event) => {
      console.error('删除所有联系人失败:', event.target.error);
      reject(event.target.error);
    };
  });
}

// 显示联系人列表
async function displayContacts(contacts = null) {
  const contactsList = document.getElementById('contacts-list');
  const emptyState = document.getElementById('empty-state');
  const contactCount = document.getElementById('contact-count');

  // 如果没有提供联系人，则从数据库获取
  if (!contacts) {
    try {
      contacts = await getAllContacts();
    } catch (error) {
      showNotification('获取联系人失败', 'error');
      return;
    }
  }

  // 更新联系人计数
  contactCount.textContent = `${contacts.length} 个联系人`;

  // 清空联系人列表
  contactsList.innerHTML = '';

  // 显示空状态或联系人列表
  if (contacts.length === 0) {
    contactsList.classList.add('hidden');
    emptyState.classList.remove('hidden');

  } else {
    contactsList.classList.remove('hidden');
    emptyState.classList.add('hidden');


    // 添加联系人到列表
    contacts.forEach(contact => {
      const contactCard = document.createElement('div');
      contactCard.className = 'contact-item';
      contactCard.dataset.id = contact.id;

      contactCard.innerHTML = `
        <div class="contact-header">
          <div class="contact-info">
            <h3>${contact.name}</h3>
            <div class="contact-details">
              <p><i class="fa fa-phone"></i>${contact.phone}</p>
              ${contact.email ? `<p><i class="fa fa-envelope"></i>${contact.email}</p>` : ''}
              ${contact.address ? `<p><i class="fa fa-home"></i>${contact.address}</p>` : ''}
            </div>
          </div>
          <div class="contact-actions">
            <button class="edit-btn" title="编辑">
              <i class="fa fa-pencil"></i>
            </button>
            <button class="delete-btn" title="删除">
              <i class="fa fa-trash-o"></i>
            </button>
          </div>
        </div>
      `;

      contactsList.appendChild(contactCard);

      // 添加编辑按钮事件
      contactCard.querySelector('.edit-btn').addEventListener('click', () => {
        loadContactForEdit(contact.id);
      });

      // 添加删除按钮事件
      contactCard.querySelector('.delete-btn').addEventListener('click', () => {
        openConfirmDialog('确认删除', `您确定要删除联系人 "${contact.name}" 吗？`, () => {
          deleteContact(contact.id)
            .then(() => {
              showNotification('联系人已删除', 'success');
              displayContacts();
            })
            .catch(error => {
              showNotification('删除联系人失败', 'error');
              console.error(error);
            });
        });
      });
    });
  }
}

// 加载联系人信息到编辑表单
async function loadContactForEdit(id) {
  try {
    const contact = await getContactById(id);
    if (contact) {
      document.getElementById('contact-id').value = contact.id;
      document.getElementById('name').value = contact.name;
      document.getElementById('phone').value = contact.phone;
      document.getElementById('email').value = contact.email || '';
      document.getElementById('address').value = contact.address || '';

      // 更新表单标题和按钮样式
      document.getElementById('form-title').innerHTML = '<i class="fa fa-pencil"></i>编辑联系人';
      document.getElementById('submit-btn').innerHTML = '<i class="fa fa-check"></i>更新';
      document.getElementById('submit-btn').classList.add('edit-mode');
      document.getElementById('contact-form').classList.add('edit-mode');

      // 滚动到表单
      document.getElementById('contact-form').scrollIntoView({ behavior: 'smooth' });
    } else {
      showNotification('联系人不存在', 'error');
    }
  } catch (error) {
    showNotification('加载联系人失败', 'error');
    console.error(error);
  }
}

// 重置表单
function resetForm() {
  document.getElementById('contact-form').reset();
  document.getElementById('contact-id').value = '';
  document.getElementById('form-title').innerHTML = '<i class="fa fa-user-plus"></i>添加联系人';
  document.getElementById('submit-btn').innerHTML = '<i class="fa fa-check"></i>保存';
  document.getElementById('submit-btn').classList.remove('edit-mode');
  document.getElementById('contact-form').classList.remove('edit-mode');
}

// 打开确认对话框
function openConfirmDialog(title, message, confirmCallback) {
  document.getElementById('dialog-title').textContent = title;
  document.getElementById('dialog-message').textContent = message;
  document.getElementById('confirm-dialog').classList.add('active');

  // 存储确认回调
  document.getElementById('dialog-confirm').onclick = () => {
    confirmCallback();
    document.getElementById('confirm-dialog').classList.remove('active');
  };

  // 取消按钮
  document.getElementById('dialog-cancel').onclick = () => {
    document.getElementById('confirm-dialog').classList.remove('active');
  };
}

// 显示通知
function showNotification(message, type = 'success') {
  const notification = document.getElementById('notification');
  const notificationIcon = document.getElementById('notification-icon');
  const notificationMessage = document.getElementById('notification-message');

  // 设置通知类型和消息
  notificationMessage.textContent = message;

  // 设置图标和背景颜色
  notification.className = 'active';
  notification.classList.remove('success', 'error', 'info');
  notification.classList.add(type);

  if (type === 'success') {
    notificationIcon.className = 'fa fa-check-circle';
  } else if (type === 'error') {
    notificationIcon.className = 'fa fa-exclamation-circle';
  } else if (type === 'info') {
    notificationIcon.className = 'fa fa-info-circle';
  }

  // 3秒后隐藏通知
  setTimeout(() => {
    notification.classList.remove('active');
  }, 3000);
}

// 搜索联系人
async function searchContacts(query) {
  try {
    const contacts = await getAllContacts();
    const filteredContacts = contacts.filter(contact => {
      const nameMatch = contact.name.toLowerCase().includes(query.toLowerCase());
      const phoneMatch = contact.phone.includes(query);
      const emailMatch = contact.email?.toLowerCase().includes(query.toLowerCase()) || false;
      const addressMatch = contact.address?.toLowerCase().includes(query.toLowerCase()) || false;

      return nameMatch || phoneMatch || emailMatch || addressMatch;
    });

    displayContacts(filteredContacts);
  } catch (error) {
    showNotification('搜索失败', 'error');
    console.error(error);
  }
}

// 按姓名排序联系人
async function sortContacts() {
  try {
    const contacts = await getAllContacts();
    const sortedContacts = [...contacts].sort((a, b) =>
      a.name.localeCompare(b.name, 'zh-CN', { sensitivity: 'base' })
    );

    displayContacts(sortedContacts);
  } catch (error) {
    showNotification('排序失败', 'error');
    console.error(error);
  }
}

// 清空所有联系人
function clearAllContacts() {
  openConfirmDialog('确认清空', '您确定要清空所有联系人吗？此操作无法撤销。', async () => {
    try {
      await deleteAllContacts();
      showNotification('所有联系人已清空', 'success');
      displayContacts();
    } catch (error) {
      showNotification('清空联系人失败', 'error');
      console.error(error);
    }
  });
}

// 初始化应用
async function initApp() {
  try {
    await initDatabase();
    await displayContacts();

    // 添加表单提交事件
    document.getElementById('contact-form').addEventListener('submit', async (event) => {
      event.preventDefault();

      const id = document.getElementById('contact-id').value;
      const name = document.getElementById('name').value;
      const phone = document.getElementById('phone').value;
      const email = document.getElementById('email').value;
      const address = document.getElementById('address').value;

      const contact = { name, phone, email, address };

      try {
        if (id) {
          // 更新联系人
          contact.id = parseInt(id);
          await updateContact(contact);
          showNotification('联系人已更新', 'success');
        } else {
          // 添加新联系人
          await addContact(contact);
          showNotification('联系人已添加', 'success');
        }

        resetForm();
        displayContacts();
      } catch (error) {
        showNotification('操作失败', 'error');
        console.error(error);
      }
    });

    // 取消按钮事件
    document.getElementById('cancel-btn').addEventListener('click', resetForm);

    // 搜索输入事件
    document.getElementById('search-input').addEventListener('input', (event) => {
      searchContacts(event.target.value);
    });

    // 排序按钮事件
    document.getElementById('sort-name').addEventListener('click', sortContacts);

    // 清空按钮事件
    document.getElementById('clear-all').addEventListener('click', clearAllContacts);
  } catch (error) {
    console.error('应用初始化失败:', error);
    showNotification('应用初始化失败', 'error');
  }
}

// 启动应用
document.addEventListener('DOMContentLoaded', initApp);
